<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use App\Http\Resources\User as UserResource;
use App\Http\Resources\UserCollection;
use App\Models\User;

class UserController extends ApiController
{

    /**
     * 用户列表
     */
    public function index(Request $request)
    {
        $limit = $request->input('size', 15);

        $orm = User::select('name', 'telphone', 'avatar', 'created_at')->orderBy('id','DESC');
        if($request->filled('keyword')){
            $keyword = $request->input('keyword');
            $pattern = '/^1([0-9]{9})/'; 
            if (preg_match($pattern, $keyword)) { 
                // 是手机号
                $orm->where('telphone', $keyword);
            }else{ 
                // 不是手机号根据昵称筛选
                $orm->where('name', 'like', '%'.$keyword.'%');
            } 
        }
        return $this->success($orm->paginate($limit));
    }

    /**
     * 显示创建用户页面
     */
    public function create() {
        // TODD
    }

    /**
     * 保存新建立用户数据
     */
    public function store() {
        // TODO
    }

    /**
     * 展示指定用户数据 
     */
    public function show($id) {
        $user = User::find($id);
        return $this->success($user);
    }

    /**
     * 查询所有个人审核信息
    */
    public function userslist(Request $request)
    {
        $limit = $request->input('size', 15);
        $myuser = User::select()->where('check', 1);  //选择未认证的个人信息
        return $this->success($myuser->paginate($limit));
        //return $this->success(User::paginate($limit)->where('check', 0));
    }


    /**
     * 个人审核
     */
    public function check($id, Request $request){
        $check = $request->input('check');
        // 做一些验证
        $user = User::find($id);

        if(!$user) {
            return $this->failed(['data' => '没有此用户', 'result' => 'fail']);
        }

        // 传递的check 为 1 审核通过
        if ($check === 2) {
            //if(!in_array($user->check, [-1 ,1])) {
            if($user->check != 1) {
                return $this->failed(['data' => '此状态不允许审核通过', 'result' => 'fail']);
            }

            $user->check = 2;
            if ($user->save()) {
                return $this->success(['data' => '个人验证通过了审核', 'result' => 'success']);
            } else {
                return $this->failed(['data' => '数据保存失败，请重试', 'result' => 'fail']);
            }
        }

        if ($check === -1 ) {
            // TODO
            if($user->check != 1) {
                return $this->failed(['data' => '此状态不允许审核通过', 'result' => 'fail']);
            }

            $user->check = -1;
            if ($user->save()) {
                return $this->success(['data' => '该用户未能通过审核', 'result' => 'fail']);
            } else {
                return $this->failed(['data' => '数据保存失败，请重试', 'result' => 'fail']);
            }
        }

        return $this->failed(['data' => '出错', 'result' => 'fail']);
    }
 
}
